package mi.payment.transaction.sale.code;

import android.annotation.SuppressLint;

import mi.payment.bean.db.TradeData;
import mi.payment.controller.BaseController;
import mi.payment.db.PayDetailModel;
import mi.payment.db.dao.PayDetail;
import mi.payment.ui.base.PageRoute;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.transaction.PollingTask;
import mi.payment.utils.transaction.QRCodeLoopingTask;

/**
 * 二维码结果轮询
 */
public class QRCodeLoopingController extends BaseController {

    private PayDetail mReqPayDetail;
    private PollingTask mPollingTask;

    private static final int TIME_OUT = 90;     // 超时时间
    private static final int RETRY_COUNT = 90;  // 重试次数

    public QRCodeLoopingController(ParentActivity activity) {
        super(activity);
    }

    @SuppressLint("StaticFieldLeak")
    public void queryQRCodeResult(TradeData tradeData) {
        mReqPayDetail = tradeData.getPayDetail();

        QRCodeLoopingTask task = new QRCodeLoopingTask(mActivity) { };
        mPollingTask = new PollingTask(RETRY_COUNT, task) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                PayDetail resPay = tradeData.getPayDetail();

                mReqPayDetail.setReferNo(resPay.referNo);
                mReqPayDetail.setThirdTransNum(resPay.thirdTransNum);
                mReqPayDetail.setTradeResultDes(resPay.tradeResultDes);
                mReqPayDetail.setTradeAnswerCode(resPay.tradeAnswerCode);
                mReqPayDetail.setQRCodeTransState(resPay.QRCodeTransState);
                // 更新数据库
                PayDetailModel.getInstance().update(mReqPayDetail);

                PageRoute.startAction(mActivity, PageRoute.TYPE_QR_CODE_CONSUME, resPay);
            }

            @Override
            protected void onTaskTimeoutImpl() {
                PageRoute.startFailAction(mActivity, PageRoute.TYPE_QR_CODE_CONSUME, mReqPayDetail);
            }

        };
        mPollingTask.setTaskTimeout(TIME_OUT);
        mPollingTask.execute(tradeData);
    }

    public void onActivityDestroy() {
        if (mPollingTask != null) {
            mPollingTask.forceStopPolling();
            mPollingTask = null;
        }
    }


}
